package com.nowcoder.community.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.benmanes.caffeine.cache.CacheLoader;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.nowcoder.community.entity.DiscussPost;
import com.nowcoder.community.entity.PageEntity;
import com.nowcoder.community.mapper.DiscussPostMapper;
import com.nowcoder.community.service.IDiscussPostService;
import com.nowcoder.community.util.SensitiveFilter;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.util.HtmlUtils;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ChenJH
 * @since 2022-12-26
 */
@Service
@Slf4j
public class DiscussPostServiceImpl extends ServiceImpl<DiscussPostMapper, DiscussPost> implements IDiscussPostService {

    @Autowired
    private SensitiveFilter sensitiveFilter;

    @Value("${caffeine.posts.max-size}")
    private int maxSize;

    @Value("${caffeine.posts.expire-seconds}")
    private int expireSeconds;

//    Caffeine核心接口: Cache,
//LoadingCache,
//AsyncLoadingCache

//    帖子列表缓存
    private LoadingCache<String, List<DiscussPost>> postListCache;
//    帖子总数缓存
    private LoadingCache<Integer,Integer> postRowsCache;

    @PostConstruct
    public void init() {
//     初始化 帖子列表 缓存
        postListCache = Caffeine.newBuilder()
                .maximumSize(maxSize)
                .expireAfterWrite(expireSeconds, TimeUnit.SECONDS)
                .build(new CacheLoader<String, List< DiscussPost>>() {
                    @Override
                    public @Nullable List<DiscussPost> load(String key) throws Exception {
//         page.setRecords(postListCache.get(pageEntity.getCurrent() + ":"+ pageEntity.getSize()));
//                        get中传入的参数就是 这里接收到的key
                        if (key == null || key.length() ==0){
                            throw new IllegalArgumentException("参数错误");
                        }
                        String[] params = key.split(":");
                        if (params == null || params.length != 2 ) {
                            throw new IllegalArgumentException("参数错误");
                        }

                        int current = Integer.parseInt(params[0]);
                        int size = Integer.parseInt(params[1]);
                        PageEntity pageEntity = new PageEntity(current,size);

                        log.info("load post list from DB");
                        return getDiscussPostList(0,pageEntity,1);
                    }
                });
//        初始化帖子总数 缓存
        postRowsCache = Caffeine.newBuilder()
                .maximumSize(maxSize)
                .expireAfterWrite(expireSeconds,TimeUnit.SECONDS)
                .build(new CacheLoader<Integer, Integer>() {
                    @Override
                    public @Nullable Integer load(Integer key) throws Exception {
                        log.info("load post rows from DB");
                        LambdaQueryWrapper<DiscussPost> wrapper = new LambdaQueryWrapper<>();
                        wrapper.ne(DiscussPost::getStatus, 2);
                        return (int)count(wrapper);
                    }
                });

    }

    public List<DiscussPost> getDiscussPostList(int userId, PageEntity pageEntity, int orderMode){
        LambdaUpdateWrapper<DiscussPost> wrapper = new LambdaUpdateWrapper<DiscussPost>()
                .ne(DiscussPost::getStatus, 2)
                .orderByDesc(DiscussPost::getType);

//        主页调取就是 id 0
        if (userId!=0){
            wrapper.eq(DiscussPost::getUserId, userId);
        }

        if (orderMode == 0){
            wrapper.orderByDesc(DiscussPost::getCreateTime);
        }else if(orderMode ==1){
            wrapper.orderByDesc(DiscussPost::getScore).orderByDesc(DiscussPost::getCreateTime);
        }

        return page(pageEntity.toPage(), wrapper).getRecords();
    }


    @Override
    public DiscussPost getDiscussPostById(int id) {
        LambdaQueryWrapper<DiscussPost> wrapper = new LambdaQueryWrapper<DiscussPost>()
                .eq(DiscussPost::getId, id)
                .ne(DiscussPost::getStatus, 2);
        return getOne(wrapper);
    }

    @Override
    public Page<DiscussPost> getDiscussPosts(int userId, PageEntity pageEntity, int orderMode) {

        if (userId ==0 && orderMode == 1){
            Page<DiscussPost> page = new Page<>();
            page.setRecords(postListCache.get(pageEntity.getCurrent() + ":"+ pageEntity.getSize()));
            page.setTotal(postRowsCache.get(0));
            page.setCurrent(pageEntity.getCurrent());
            page.setSize(pageEntity.getSize());


            return  page;
        }


        LambdaUpdateWrapper<DiscussPost> wrapper = new LambdaUpdateWrapper<DiscussPost>()
                .ne(DiscussPost::getStatus, 2)
                .orderByDesc(DiscussPost::getType);

//        主页调取就是 id 0
        if (userId!=0){
            wrapper.eq(DiscussPost::getUserId, userId);
        }

        if (orderMode == 0){
            wrapper.orderByDesc(DiscussPost::getCreateTime);
        }else if(orderMode ==1){
            wrapper.orderByDesc(DiscussPost::getScore).orderByDesc(DiscussPost::getCreateTime);
        }
        log.info("load posts  from DB");
        return page(pageEntity.toPage(), wrapper);
    }

    @Override
    public boolean addDiscussPost(DiscussPost discussPost) {
        if (discussPost == null) {
            throw new IllegalArgumentException("参数不能为空");
        }
//        转义html标签 避免对浏览器做出什么破坏
//        比如在标题或文章内部添加了<script>
        discussPost.setTitle(HtmlUtils.htmlEscape(discussPost.getTitle()));
        discussPost.setContent(HtmlUtils.htmlEscape(discussPost.getContent()));
//        过滤敏感词
        discussPost.setTitle(sensitiveFilter.filter(discussPost.getTitle()));
        discussPost.setContent(sensitiveFilter.filter(discussPost.getContent()));

        return save(discussPost);
    }

    @Override
    public boolean updateCommentCount(int id, long commentCount) {
        LambdaUpdateWrapper<DiscussPost> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(DiscussPost::getId,id);
        wrapper.set(DiscussPost::getCommentCount,commentCount);
        return update(wrapper);
    }

    @Override
    public boolean updateType(int id, int type) {
        LambdaUpdateWrapper<DiscussPost> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(DiscussPost::getId,id)
                .set(DiscussPost::getType,type);
        return update(wrapper);
    }

    @Override
    public boolean updateStatus(int id, int status) {
        LambdaUpdateWrapper<DiscussPost> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(DiscussPost::getId,id)
                .set(DiscussPost::getStatus,status);
        return update(wrapper);
    }

    @Override
    public boolean updateScore(int id, double score) {
        LambdaUpdateWrapper<DiscussPost> wrapper = new LambdaUpdateWrapper<DiscussPost>()
                .eq(DiscussPost::getId, id)
                .set(DiscussPost::getScore, score);
        return update(wrapper);
    }


}
